package assembler;

import java.io.*;
import java.util.Vector;

class AsmFileReader
{

    public AsmFileReader(String s)
    {
        filename = s;
        done = false;
        lineno = 0;
        try
        {
            reader = new BufferedReader(new FileReader(s));
        }
        catch(FileNotFoundException filenotfoundexception)
        {
            System.out.println("Erro: Impossível abrir " + s + ".");
            System.exit(-1);
        }
    }

    public Vector nextLine()
    {
        if(!done)
        {
            Vector vector;
            for(vector = nextRawLine(); vector != null && (vector.size() == 1 || ((String)vector.elementAt(1)).startsWith("*")); vector = nextRawLine()) { }
            return vector;
        } else
        {
            return null;
        }
    }

    private Vector nextRawLine()
    {
        String s = "";
        Vector vector = new Vector(5, 8);
        try
        {
            String s1 = reader.readLine();
            lineno++;
            if(s1 != null)
            {
                vector.addElement(new Integer(lineno));
                while(s1.length() > 0) 
                {
                    int i = s1.lastIndexOf(' ');
                    i = Math.max(i, s1.lastIndexOf('\t'));
                    i = Math.max(i, s1.lastIndexOf(','));
                    String s2;
                    if(i == -1)
                    {
                        s2 = s1;
                        s1 = "";
                    } else
                    {
                        s2 = s1.substring(i + 1, s1.length());
                        s1 = s1.substring(0, i);
                    }
                    s2 = s2.trim();
                    if(s2.startsWith("*"))
                    {
                        vector.removeAllElements();
                        vector.addElement(new Integer(lineno));
                        s2 = "";
                    }
                    if(!s2.equals(""))
                    {
                        vector.add(1, s2.trim());
                    }
                }
                return vector;
            } else
            {
                done = true;
                return null;
            }
        }
        catch(IOException ioexception)
        {
            System.out.println("Erro: Leitura errada em " + filename + ".");
            System.out.println(ioexception);
            System.exit(-1);
            return null;
        }
    }

    public static void main(String args[])
    {
        AsmFileReader asmfilereader = new AsmFileReader("test.asm");
        for(Vector vector = asmfilereader.nextLine(); vector != null; vector = asmfilereader.nextLine())
        {
            System.out.println(vector);
        }

    }

    private BufferedReader reader;
    private String filename;
    private boolean done;
    private int lineno;
}
